const {Toast} = require('antd-mobile');
const {Actions} = require("react-native-router-flux");
import {default as constant, ERROR_MSG_DURATION} from './constant'

const {Linking} = require("react-native");

export const distanceStr = (distance) => {
    const d = distance > 1000 ? distance / 1000 : distance
    const unit = distance > 1000 ? 'Km' : 'm'
    return `${Math.ceil(d * 100) / 100}${unit}`
}

export const tookQty = (qty) => {

    if (qty == 0) {
        return 30
    }
    if (qty <= 5 && qty < 10) {
        return Math.ceil(qty * 10 + parseInt(qty))
    }
    if (qty < 100) {
        return Math.ceil(qty * 1.5)
    }
    return qty
}

export const chooseRate = (rate) => {
    if (rate > 100) {
        return 99
    }
    return rate
}

export const checkToken = (auth, fail = null) => {

    if (auth instanceof Object && Object.keys(auth).length > 0) {

        if (auth.isSignIn) {

            if (auth.profile instanceof Object && Object.keys(auth.profile).length > 0) {

                if (auth.profile.token && auth.profile.token.length > 0) {

                    return true
                }
            }
        }
    }
    fail && fail()
    return false
}

export const checkResponse = (data, code = [402, 403], msg = '账户信息已过期，或者在其他地方登陆过,请重新登录') => {
    let success = true
    if (code instanceof Array) {
        for (let i = 0; i < code.length; i++) {
            if (code[i] == data.code) {
                success = false
                break
            }
        }
    } else if (code == data.code) {
        success = false
    }
    if (!success) {
        if (msg) {
            Toast.fail(msg, 1.5)
        }
    }
    return success
}

export const checkSns = (auth, channel = '') => {
    let info = null
    if (auth.profile.sns && auth.profile.sns.length > 0) {
        auth.profile.sns.map((sns) => {
            if (sns.platform == 'web' && sns.channel == channel) {
                info = sns
            }
        })
    }
    if (auth.sns && auth.sns.length > 0) {
        auth.profile.sns.map((sns) => {
            if (sns.platform == 'web' && sns.channel == channel) {
                info = sns
            }
        })
    }
    return info
}

export function array_chunk(input, size, preserve_keys) {
    // *     example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
    // *     returns 1: [['Kevin', 'van'], ['Zonneveld']]
    // *     example 2: array_chunk(['Kevin', 'van', 'Zonneveld'], 2, true);
    // *     returns 2: [{0:'Kevin', 1:'van'}, {2: 'Zonneveld'}]
    // *     example 3: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2);
    // *     returns 3: [['Kevin', 'van'], ['Zonneveld']]
    // *     example 4: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2, true);
    // *     returns 4: [{1: 'Kevin', 2: 'van'}, {3: 'Zonneveld'}]

    let x, p = '', i = 0, c = -1, l = input.length || 0, n = []

    if (size < 1) {
        return null
    }

    if (Object.prototype.toString.call(input) === '[object Array]') {
        if (preserve_keys) {
            while (i < l) {
                (x = i % size) ? n[c][i] = input[i] : n[++c] = {}, n[c][i] = input[i]
                i++
            }
        }
        else {
            while (i < l) {
                (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]]
                i++
            }
        }
    }
    else {
        if (preserve_keys) {
            for (p in input) {
                if (input.hasOwnProperty(p)) {
                    (x = i % size) ? n[c][p] = input[p] : n[++c] = {}, n[c][p] = input[p]
                    i++
                }
            }
        }
        else {
            for (p in input) {
                if (input.hasOwnProperty(p)) {
                    (x = i % size) ? n[c][x] = input[p] : n[++c] = [input[p]]
                    i++
                }
            }
        }
    }
    return n
}

/**
 * 错误轻提示
 * @param errors
 * @param message
 */
export const toastValidateError = (errors, message = '') => {
    errors && Object.keys(errors).map((errorKey) => {
        errors[errorKey].errors.map((e, i) => {
            message += e.message + (errors[errorKey].errors.length - 1 !== i ? '' : "\n");
        });
    });
    Toast.fail(message, ERROR_MSG_DURATION);
};

/**
 * 成功轻提示
 * @param errors
 * @param message
 */
export const toastValidateSuccess = (errors, message = '') => {
    errors && Object.keys(errors).map((errorKey) => {
        errors[errorKey].errors.map((e, i) => {
            message += e.message + (errors[errorKey].errors.length - 1 !== i ? '' : "\n");
        });
    });
    Toast.success(message, ERROR_MSG_DURATION);
};


/**
 * 从数组中获取指定key的值
 * @param {any[]} array
 * @param {string} field
 * @param value
 * @return any
 */
export const getValueFromArray = (array: any[], field: string, value: any) => {
    let _value = null;
    if (!field) {
        return _value;
    }
    if (!value) {
        return _value;
    }

    _value = [];
    array.map(item => {
        if (typeof item === 'string') {
            if (item === value) {
                _value.push(item[field]);
            }
        } else if (typeof item === 'object') {
            if (item [field] === value) {
                _value.push(item[field]);
            }
        }
    });
    if (_value.length === 0) {
        return null;
    }
    else if (_value.length === 1) {
        return _value[0];
    } else {
        return _value;
    }
};


/**
 *  使用浏览器打开 url
 * @param {string} source
 * @param {boolean} inApp app内打开
 */
export const openUrl = (source: any, inApp = false) => {
    if (inApp) {
        Actions.web({source});
    } else {
        Linking.canOpenURL(source).then(supported => {
            if (!supported) {
                Toast.fail('无法打开链接:' + source, constant.ToastDuration);
            } else {
                return Linking.openURL(source);
            }
        }).catch(err => {
            // console.log('打开链接出现异常', err);
            Toast.error(err.message, constant.ToastDuration);
        });
    }

};


/**
 * 检查角色能否登录
 * @param {roleItem[]} roles
 * @return {boolean}
 */
export const checkRole = (roles: roleItem[]) => {
    if (!roles || roles.length <= 0) return false;
    // normal
    const roleStr = roles.map((r: roleItem) => r.code).join('|');
    if (roleStr.indexOf('market') !== -1) {
        return false;
    }
    if (roleStr.indexOf('normal') !== -1) {
        return false;
    }
    return true;
};

